package com.rykj.qxj.rest;

import com.github.pagehelper.PageInfo;
import com.rykj.qxj.annotation.EnableSystemLog;
import com.rykj.qxj.server.model.entity.Task;
import com.rykj.qxj.server.services.IQuartzService;
import com.rykj.qxj.server.services.ITaskService;
import com.rykj.qxj.server.util.object.StringUtils;
import com.rykj.qxj.util.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j;
import org.quartz.CronExpression;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@Log4j
@RestController
@RequestMapping("/v1/task")
@Api(tags="字段校验任务")
public class TaskController {

    @Autowired
    private ITaskService taskService;



    @PostMapping("/saveTask")
    @ApiOperation(value="添加任务",notes ="添加任务")
    @EnableSystemLog(value="修改规则",fullPath ="/v1/task/saveTask")
    public Result saveTask(@RequestBody Task task){
        try{
            List<Integer> taskIds = taskService.getTaskIdByName(task.getTaskName());
            if(!CollectionUtils.isEmpty(taskIds)){
                return new Result(false,"任务名称已存在");
            }
            taskService.saveTask(task);
            return new Result(true,"添加成功");
        }catch (Exception e){
            log.error("添加失败", e);
            return new Result(false, "添加失败");
        }
    }

    @PostMapping("/updateTask")
    @ApiOperation(value="修改任务",notes ="修改任务")
    @EnableSystemLog(value="修改任务",fullPath ="/v1/task/updateTask")
    public Result updateTask(@RequestBody Task task){
        try{
            if(!CronExpression.isValidExpression(task.getExecuteRate())){
                return  new Result(false,"执行时间频率表达式有误");
            }
            List<Integer> taskIds = taskService.getTaskIdByName(task.getTaskName());
            if(!CollectionUtils.isEmpty(taskIds) &&
                    (taskIds.size()>1 || taskIds.get(0)!=task.getId())){
                return new Result(false,"任务名称已存在");
            }
            taskService.updateTask(task);
            return new Result(true,"修改成功");
        }catch (Exception e){
            log.error("修改失败", e);
            return new Result(false, "修改失败");
        }
    }

    @GetMapping("/deleteTask")
    @ApiOperation(value="删除任务",notes ="删除任务")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id主键",required = true,paramType = "query"),
            @ApiImplicitParam(name = "taskName", value = "任务名称",required = true,paramType = "query")
    })
    @EnableSystemLog(value="删除任务",fullPath ="/v1/task/deleteTask")
    public Result deleteTask(@RequestParam(value = "id") Integer id,
                             @RequestParam(value = "taskName") String taskName){
        try{
            taskService.deleteTask(id,taskName);

            return new Result(true,"删除成功");
        }catch (Exception e){
            log.error("删除失败", e);
            return new Result(false, "删除失败");
        }
    }

    @GetMapping("/getTaskDetails")
    @ApiOperation(value="获取任务详情",notes ="获取任务详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = " id主键",required = true,paramType = "query")
    })
    public Result getTaskDetails(@RequestParam(value = "id") Integer id){
        try{
            Task task = taskService.getTaskDetails(id);
            return new Result(task);
        }catch (Exception e){
            log.error("获取任务详情失败", e);
            return new Result(false, "获取任务详情失败");
        }
    }

    @GetMapping("/getTaskList")
    @ApiOperation(value="分页获取任务列表",notes ="分页获取任务列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "当前页数",required = true,paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "显示行数",required = true,paramType = "query"),
            @ApiImplicitParam(name = "taskName", value = "任务名称",paramType = "query"),
            @ApiImplicitParam(name = "tableName", value = "表名称",paramType = "query"),
            @ApiImplicitParam(name = "executeType", value = "执行类型",paramType = "query"),
            @ApiImplicitParam(name = "taskStatus", value = "任务状态: 启用enable，禁止disable",paramType = "query"),
            @ApiImplicitParam(name = "applyId", value = "应用id",paramType = "query"),
            @ApiImplicitParam(name = "databaseId", value = "数据库",paramType = "query"),
            @ApiImplicitParam(name = "tableId", value = "表id",paramType = "query")
    })
    public Result getTaskList(@RequestParam(value = "pageNum") Integer pageNum,
                              @RequestParam(value = "pageSize") Integer pageSize,
                              @RequestParam(value = "taskName",required=false) String taskName,
                              @RequestParam(value = "tableName",required=false) String tableName,
                              @RequestParam(value = "executeType",required=false) String executeType,
                              @RequestParam(value = "taskStatus",required=false) String taskStatus,
                              @RequestParam(value = "applyId",required=false) Integer applyId,
                              @RequestParam(value = "databaseId",required=false) Integer databaseId,
                              @RequestParam(value = "tableId",required=false) Integer tableId){
        try{
            PageInfo pager =  taskService.getTaskList(pageNum,pageSize,taskName,tableName,executeType,taskStatus,applyId,databaseId,tableId);
            return new Result(pager);
        }catch (Exception e){
            log.error("分页获取任务列表失败", e);
            return new Result(false, "分页获取任务列表失败");
        }
    }

    @GetMapping("/getAuditMetadataList")
    @ApiOperation(value="分页获取校验的字段列表",notes ="分页获取校验的字段列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "当前页数",required = true,paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "显示行数",required = true,paramType = "query"),
            @ApiImplicitParam(name = "taskId", value = "任务id",required = true,paramType = "query")
    })
    public Result getAuditMetadataList(@RequestParam(value = "pageNum") Integer pageNum,
                              @RequestParam(value = "pageSize") Integer pageSize,
                              @RequestParam(value = "taskId") Integer taskId){
        try{
            PageInfo pager =  taskService.getAuditMetadataList(pageNum,pageSize,taskId);
            return new Result(pager);
        }catch (Exception e){
            log.error("分页获取校验的字段列表失败", e);
            return new Result(false, "分页获取校验的字段列表失败");
        }
    }

    @GetMapping("/getUnTaskFields")
    @ApiOperation(value="分页获取未建任务规则的字段",notes ="分页获取未建任务规则的字段")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "当前页数",required = true,paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "显示行数",required = true,paramType = "query"),
            @ApiImplicitParam(name = "tableId", value = "表id",required = true,paramType = "query")
    })
    public Result getUnTaskFields(@RequestParam(value = "pageNum") Integer pageNum,
                                  @RequestParam(value = "pageSize") Integer pageSize,
                                  @RequestParam(value = "tableId") Integer tableId){
        try{
            PageInfo pager =  taskService.getUnTaskFields(pageNum,pageSize,tableId);
            return new Result(pager);
        }catch (Exception e){
            log.error("分页获取未建任务规则的字段失败", e);
            return new Result(false, "分页获取未建任务规则的字段失败");
        }
    }

    @GetMapping("/updateTaskStatus")
    @ApiOperation(value="禁用或启用任务",notes ="禁用或启用任务")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "taskStatus", value = "任务状态: 启用enable，禁止disable",required = true,paramType = "query"),
            @ApiImplicitParam(name = "taskName", value = "任务名称",required = true,paramType = "query"),
            @ApiImplicitParam(name = "taskId", value = "任务id",required = true,paramType = "query"),
            @ApiImplicitParam(name = "time", value = "任务执行频率",required = true,paramType = "query")

    })
    @EnableSystemLog(value="禁用或启用任务",fullPath ="/v1/task/updateTaskStatus")
    public Result updateTaskStatus(@RequestParam(value = "taskStatus") String taskStatus,
                                   @RequestParam(value = "taskName") String taskName,
                                   @RequestParam(value = "taskId") Integer taskId,
                                   @RequestParam(value = "time") String time){
        try{
            if("enable".equals(taskStatus) && StringUtils.isNotEmpty(time)){
                CronExpression exp = new CronExpression(time);
                Date cronDate = exp.getNextValidTimeAfter(new Date());
                Date nowDate = new Date();
                if (cronDate==null || cronDate.compareTo(nowDate)==-1){
                    return new Result(false,"该任务永远无法执行，请修改执行频率后再启用");
                }
            }
           taskService.updateTaskStatus(taskStatus,taskId,taskName,time);
           return new Result(true,"操作成功");
        }catch (Exception e){
            log.error("操作失败", e);
            return new Result(false, "操作失败");
        }
    }



}
